<?php
namespace app\admin\controller\auth;
use app\admin\model\AuthRule;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use think\Cache;
use fast\Tree;
use fast\Random;
use fast\Cols;
use fast\Date;

/**
 * 部门管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Department extends Backend
{
    protected $model = null;
    protected $rulelist = [];
    protected $multiFields = 'ismenu,status';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    public function initialize()
    {
        parent::initialize();
        $this->model = model('Department');
        //$this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    public function index()
    {
		$columnlist = Cols::columnread('department');
		$flag = array();$options = array();
		foreach($columnlist as $v){
			$flag[] = $v['listorder'];
            if($v['options']&&$v['isshowlist']==1){
                //把带有选项的列，提取出来。
                $options[$v['columnenname']] = $v['options'];
            }
		}
		array_multisort($flag, SORT_ASC, $columnlist);
		//设置过滤方法
		$this->request->filter(['strip_tags']);
		//如果发送的来源是Selectpage，则转发到Selectpage
		if ($this->request->request('pkey_name')){
				return $this->selectpage();
		}
		$searchfileds = array();
        $searchdefault = array();
		$searchfileds['name'] = 'varcharshort';
        $searchfileds['pid'] = 'varcharshort';
		list($where, $sort, $order, $offset, $limit) = $this->buildparams($searchfileds);
        $limit = 300;
		$order = 'desc';
		$sort = 'listorder';
		$total = $this->model->where($where)->order($sort, $order)->count();
		$totalpage = 1;$page = 1;
		if($limit>0){
				$totalpage = $total%$limit==0?intval($total/$limit):intval($total/$limit)+1;
				//总页数
				if($offset>0){$page = intval($offset/$limit)+1;}
		}
        //print_r($where);exit;
		$list = $this->model
		->where($where)
		->order($sort, $order)
		->limit($offset, $limit)
		->select();
		for ($i = 0; $i < count($list); $i++) {
			if(isset($list[$i]['category'])){
					$list[$i]['catname'] = $list[$i]['category']['name'];
			}
			unset($list[$i]['intro']);unset($list[$i]['content']);
            foreach ($options as $k => $v) {
                if(isset($list[$i][$k])){
                    $arj = json_decode($v,true);
                    $sarj = $arj[$list[$i][$k]];
                    $list[$i][$k] = $sarj;
                }
            }
		}

		$result = array("total" => $total, "rows" => $list);
		$this->view->assign("lists",$result['rows']);
		$this->view->assign("listsjson",json_encode($result['rows']));
        $this->view->assign("columnlistjson",json_encode($columnlist));
        $this->view->assign("columnlist",$columnlist);
		$this->view->assign("total",$result['total']);
		$this->view->assign("offset",$offset);
		$this->view->assign("limit",$limit);
		$this->view->assign("totalpage",$totalpage);
		$this->view->assign("page",$page);
		return $this->view->fetch('index');
	}
    //添加
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {
                  $params['itemid'] = str_replace('-','',Random::uuid());
                  $result = $this->model->save($params);
                  if ($result === false)
                  {
                      $this->error($this->model->getError());
                  }

                  $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }
    //编辑
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['itemid' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params)
            {

                $result = $row->save($params);
                if ($result === false)
                {
                   $this->error($row->getError());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        //$this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }


    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    protected function selectpage()
    {
        // $this->dataLimit = 'auth';
        // $this->dataLimitField = 'id';
        return parent::selectpage();
    }
}
